package com.yupi.yuaiagent.tools;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 网页搜索工具
 */
public class WebSearchTool {

    // SearchAPI 的搜索接口地址
    private static final String SEARCH_API_URL = "https://www.searchapi.io/api/v1/search";

    private final String apiKey;

    public WebSearchTool(String apiKey) {
        this.apiKey = apiKey;
    }

//    @Tool(description = "Search for information from Baidu Search Engine")
//    public String searchWeb(
//            @ToolParam(description = "Search query keyword") String query) {
//        Map<String, Object> paramMap = new HashMap<>();
//        paramMap.put("q", query);
//        paramMap.put("api_key", apiKey);
//        paramMap.put("engine", "baidu");
//        try {
//            String response = HttpUtil.get(SEARCH_API_URL, paramMap);
//            // 取出返回结果的前 5 条
//            JSONObject jsonObject = JSONUtil.parseObj(response);
//            // 提取 organic_results 部分
//            JSONArray organicResults = jsonObject.getJSONArray("related_searches");
//            List<Object> objects = organicResults.subList(0, 5);
//            // 拼接搜索结果为字符串
//            String result = objects.stream().map(obj -> {
//                JSONObject tmpJSONObject = (JSONObject) obj;
//                return tmpJSONObject.toString();
//            }).collect(Collectors.joining(","));
//            return result;
//        } catch (Exception e) {
//            return "Error searching Baidu: " + e.getMessage();
//        }
//    }

    @Tool(description = "Search for information from Baidu Search Engine")
    public String searchWeb(
            @ToolParam(description = "Search query keyword") String query) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("q", query);
        paramMap.put("api_key", apiKey);
        paramMap.put("engine", "bing");
        try {
            String response = HttpUtil.get(SEARCH_API_URL, paramMap);
            JSONObject jsonObject = JSONUtil.parseObj(response);
            // 提取搜索结果列表
            JSONArray organicResults = jsonObject.getJSONArray("organic_results");

            // 处理前5条结果，清理每个结果中的所有值
            List<String> cleanedResults = new ArrayList<>();
            for (int i = 0; i < Math.min(3, organicResults.size()); i++) {
                JSONObject result = organicResults.getJSONObject(i);

                // 遍历每个结果中的所有键值对，清理并拼接
                StringBuilder resultBuilder = new StringBuilder();
                for (String key : result.keySet()) {
                    Object value = result.get(key);
                    if (value != null) {
                        // 清理字符串值
                        String cleanedValue = cleanText(value.toString());
                        resultBuilder.append(key).append(": ").append(cleanedValue).append("\n");
                    }
                }
                cleanedResults.add(resultBuilder.toString().trim());
            }
            // 使用分隔线连接不同结果
            return String.join("\n\n---\n\n", cleanedResults);
        } catch (Exception e) {
            return "Error searching Baidu: " + e.getMessage();
        }
    }

    // 清理文本：去除HTML标签和多余空格
    private String cleanText(String text) {
        if (text == null) return "";

        // 去除HTML标签
        text = text.replaceAll("<[^>]+>", "");

        // 合并连续空格和换行符为单个空格
        text = text.replaceAll("\\s+", " ");

        // 去除首尾空格
        return text.trim();
    }
}
